const express = require("express")
const router = express.Router()
const journalDB = require("../../../db/journal")
const shareDB = require("../../../db/share")

// 权限判断
router.use((req, res, next) => {
  if (!req.session.userInfo.allowDelete) {
    return res.send({
      code: 15,
      mes: "您没有删除权限，请联系超级管理员进行添加"
    })
  }
  next()
})

// 删除评论
router.post("/", async (req, res) => {
  try {
    let { _id, articleID } = req.body


    // 检测文章是否存在
    let articleInfo = await journalDB.findById(articleID)
    if (!articleInfo) {
      articleInfo = await shareDB.findById(articleID)
    }

    const commentInfo = articleInfo.comment?.id(_id)

    if (!commentInfo) return res.send({
      mes: '该评论已删除',
      code: 12
    })
    // 删除评论
    await journalDB.findByIdAndUpdate(articleID,
      {
        $pull:
        {
          comment: commentInfo
        }
      }
    )
    await shareDB.findByIdAndUpdate(articleID,
      {
        $pull:
        {
          comment: commentInfo
        }
      }
    )



    res.send({
      code: 0,
      mes: "删除成功",
    })
  } catch (error) {
    res.send({
      code: 5,
      mes: "服务器异常，请稍后再试"
    })
  }
})

module.exports = router